package com.da.lon.wang.xlg.view;

import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.da.lon.wang.xlg.R;

public class TimeDownView extends RelativeLayout implements Runnable {

    private TextView timedown_day, timedown_hour, timedown_min,
            timedown_second;
    private Paint mPaint; // 画笔,包含了画几何图形、文本等的样式和颜色信息
    private long times;
    private int mhour, mmin, msecond;// 天，小时，分钟，秒
    private boolean run = false; // 是否启动了

    public TimeDownView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }

    public TimeDownView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public TimeDownView(Context context) {
        super(context);
        initView(context);
    }

    private void initView(Context context) {
        View.inflate(context, R.layout.timedown_layout, TimeDownView.this);
        timedown_hour = (TextView) this.findViewById(R.id.timedown_hour);
        timedown_min = (TextView) this.findViewById(R.id.timedown_min);
        timedown_second = (TextView) this.findViewById(R.id.timedown_second);

        mPaint = new Paint();
    }

    public long getTimes() {
        return times;
    }

    public void setTimes(long times) {
        this.times = times;
        mhour = (int) times / 3600;
        mmin = (int) ((times % 3600) / 60);
        msecond = (int) times % 60;
    }

    /**
     * 倒计时计算
     */
    private void ComputeTime() {
        this.times--;
        msecond--;
        if (times < 0) {
            // 中断线程
            Thread.currentThread().interrupt();
        }
        if (msecond < 0) {
            mmin--;
            msecond = 59;
            if (mmin < 0) {
                mmin = 59;
                mhour--;
                if (mhour < 0) {
                    // 倒计时结束
                    mhour = 59;
                }
            }
        }
    }

    public boolean isRun() {
        return run;
    }

    public void setRun(boolean run) {
        this.run = run;
    }

    @Override
    public void run() {
        // 标示已经启动
        run = true;
        ComputeTime();
        if (mhour < 10) {
            timedown_hour.setText("0" + mhour + "");
        } else {
            timedown_hour.setText(mhour + "");
        }
        if (mmin < 10) {
            timedown_min.setText("0" + mmin + "");
        } else {
            timedown_min.setText(mmin + "");
        }
        if (msecond < 10) {
            timedown_second.setText("0" + msecond + "");
        } else {
            timedown_second.setText(msecond + "");
        }
//		LogUtils.v("当前倒计时："+mhour+":"+mmin+":"+msecond);
        postDelayed(this, 1000);
    }

}
